package web;

import domain.User;
import service.UserService;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/queryPageServlet")
public class QueryPageServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //分页功能实现,使用物理查询,从sql语句入手,发现需要传递页面在第几页和每页需要显示的数量
        String pagestr = request.getParameter("page");
        String countstr = request.getParameter("count");

        //类型转换
        int page = Integer.parseInt(pagestr);
        int count = Integer.parseInt(countstr);
        int offset = (page - 1) * count;

        //处理业务数据
        UserService service = new UserServiceImpl();
        //调用查询方法
        List<User> list = service.queryPage(offset, count);
        //完成徐需求:分页按钮的数量由数据库的数据量决定,
        int sum = service.findSum();
        //根据查询的总数量和每页需要显示几条的数据得到需要多少分页按钮
        int pageSum = sum % count == 0 ? sum / count : sum / count + 1;



        //查询完之后将数据返回前端
        request.getSession().setAttribute("list", list);//用户的总数
        //将page参数传递回去,完成分页按钮高亮显示
        request.getSession().setAttribute("page", page);
        //完成页面按钮的总数量的需求
        request.getSession().setAttribute("pageSum",pageSum);
        //每页需要显示的数量
        request.getSession().setAttribute("count",count);
        response.sendRedirect("/list.jsp");
    }

}
